package handler

import (
	"app-sys-ctrl/cache"
	"app-sys-ctrl/model"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func Add(c *gin.Context) {
	appName := c.PostForm("appName")
	appDoc := c.PostForm("appDoc")
	data := model.App{
		AppName: appName,
		AppDoc:  appDoc,
	}
	err := model.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	var app model.App
	redis_key := "add_" + strconv.Itoa(int(data.ID))
	model.DB.Where("id=?", data.ID).First(&app)
	jsonData, _ := json.Marshal(app)
	cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}

func TypeList(c *gin.Context) {
	var types []model.Types
	redis_key := "add"
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Debug().Find(&types)
		jsonData, _ := json.Marshal(types)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": types,
	})
	return
}

func List(c *gin.Context) {
	var app []model.App
	redis_key := "add"
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Debug().Find(&app)
		jsonData, _ := json.Marshal(app)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": app,
	})
	return
}
